import requests
from requests_toolbelt import MultipartEncoder
import os
import json


def SendMessage(msg=None, image=None):
    FEISHU_BOT_API = os.environ.get("FEISHU_BOT_API")
    if FEISHU_BOT_API is None:
        raise RuntimeError("没有设置环境变量 FEISHU_BOT_API")

    url = FEISHU_BOT_API
    headers = {
        "Content-Type": "application/json"
    }
    if msg is not None:
        data = {
            "msg_type": "text",
            "content": {
                "text": msg
            }
        }
        response = requests.post(url, headers=headers, data=json.dumps(data))
        if json.loads(response.text).get("StatusMessage","") == "success":
            return True
        else:
            return False
    if image is not None:
        fileKey = UploadImage(image)
        data = {
            "msg_type": "image",
            "content": {
                "image_key": fileKey
            }
        }
        response = requests.post(url, headers=headers, data=json.dumps(data))
        if json.loads(response.text).get("StatusMessage","") == "success":
            return True
        else:
            return False
    return True


def GetToken():
    FEISHU_APP_ID = os.environ.get("FEISHU_APP_ID")
    FEISHU_APP_SECRET = os.environ.get("FEISHU_APP_SECRET")
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "app_id": FEISHU_APP_ID,
        "app_secret": FEISHU_APP_SECRET
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))
    data = json.loads(response.text)
    if data.get("msg") == "ok":
       return data.get("tenant_access_token")
    else:
       raise RuntimeError("获取token失败")


def UploadImage(filepath):
    filename = filepath.split("/")[-1]
    url = "https://open.feishu.cn/open-apis/im/v1/images"
    form = {'image_type': 'message', 'image': (open(filepath, 'rb'))}
    multi_form = MultipartEncoder(form)
    headers = {
      'Authorization': 'Bearer {}'.format(GetToken()),
    }
    headers['Content-Type'] = multi_form.content_type
    response = requests.request("POST", url, headers=headers, data=multi_form)
    data = json.loads(response.text)
    if data.get("msg") == "success":
        return data.get("data").get("image_key")
    else:
        raise RuntimeError("上传文件失败")


if __name__ == "__main__":
    SendMessage(None, "115414670134103540.jpg")
